import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'function.dart';
import 'model/device_model.dart';
import 'package:fcharts/fcharts.dart';
import 'package:flutter/animation.dart';
class IncomeRecordPage extends StatefulWidget {
  IncomeRecordPage({this.id, this.device_name});
  final String device_name;
  final int id;
  @override
  _IncomeRecordPageState createState() => new _IncomeRecordPageState(id, device_name);
}

class Income {
  const Income(this.date, this.income);
  final int date;
  final double income;
}

class _IncomeRecordPageState extends State<IncomeRecordPage> {
  double totalIncome = 0.0;
  List<Income> incomeArr = [];
  bool has_next = false;
  int has_data=2;
  final int id;
  final String device_name;
  DeviceModel device;
  double maxIncome = 0.1;
  int maxDay=31;
  _IncomeRecordPageState(this.id, this.device_name) {
    initDevice();
  }
  back(){
    Navigator.pop(context);
  }
  initDevice() async {
    this.device = new DeviceModel().fromMap(await findDeviceById(id));
    incomeRecord();
  }

  incomeRecord() async {
    var isLogin = await checkLogin(device.sessionid, device.userid);
    bool loginStatus = true;
    if (!isLogin) {
      Map loginInfo = await doLogin(id: device.id, account: device.account, password: device.password, deviceid: device.device_id, imeiid: device.imeiid);
      if (loginInfo != null) {
        print("重新登录成功");
        device.sessionid = loginInfo['sessionid'];
        device.userid = loginInfo['userid'];
      } else {
        loginStatus = false;
      }
    }
    if (loginStatus) {
      print("登录有效");
      Map incomeData = await getIncomeRecord(sessionid: device.sessionid, userid: device.userid,year: 2018,month: 7);
      this.has_data=incomeData['has_data']?1:0;
      print(this.has_data);
      this.has_next=incomeData['has_next'];
      if(incomeData['has_data']==false&&incomeData['has_next']==false){
        setState(() {});
        return ;
      }
      for (int i = incomeData['incomeArr'].length; i > 0; i--) {
        var income = incomeData['incomeArr'][i - 1];
        int dateAdd = int.parse(income['date']);
        double incomeAdd = double.parse(income['num']);
        this.incomeArr.add(new Income(dateAdd % 100, incomeAdd));
        if (incomeAdd > maxIncome) {
          maxIncome = incomeAdd;
        }
        maxDay=dateAdd%100;
      }
      double total = incomeData['totalIncome'];
      this.totalIncome = total;
      this.has_next = incomeData['nextPage'];
      setState(() {});
    } else {
      showDialog<Null>(
        context: context,
        builder: (ctx) {
          return new AlertDialog(
            title: new Text("错误提醒"),
            content: new Text("获取提币记录失败，请重试"),
            actions: <Widget>[
              new FlatButton(
                onPressed: () async {
                  incomeRecord();
                },
                child: new Text(
                  '重试',
                ),
              ),
              new FlatButton(
                onPressed: () async {
                  back();
                },
                child: new Text(
                  '返回',
                ),
              ),
            ],
          );
        },
      );
    }
  }

  Widget _buildTiles(Income income) {
    return new Column(
      children: <Widget>[
        new ListTile(
          title: new Text(
            income.date.toString()+"日",
            style: new TextStyle(fontSize: 16.0),
          ),
          trailing: new Text(
            income.income.toString(),
            style: new TextStyle(fontSize: 22.0, color: Colors.deepOrangeAccent),
          ),
        ),
        Divider(height: 1.0),
      ],
    );
  }

  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      theme: new ThemeData(
        accentColor: Colors.deepOrange,
        primaryColor: Colors.deepOrange,
      ),
      home: new Scaffold(
        appBar: new CupertinoNavigationBar(
          actionsForegroundColor: Colors.white,
          backgroundColor: Colors.deepOrange,
          middle: new Text(
            (this.device_name ?? "") + "历史收入",
            style: new TextStyle(
              color: Colors.white,
              fontWeight: FontWeight.normal,
            ),
          ),
          leading: new CupertinoButton(
            padding: EdgeInsets.all(0.0),
            child: new Icon(
              CupertinoIcons.back,
              color: Colors.white,
            ),
            onPressed: () {
              Navigator.pop(context, "0");
            },
          ),
        ),
        body: this.has_data==1?new Column(
          children: <Widget>[
            new Container(
              height: 200.0,
              decoration: new BoxDecoration(
                border: new Border(bottom: new BorderSide(color: Colors.black12,width: 1.0),)
              ),
              padding: EdgeInsets.only(left: 20.0, right: 20.0),
              child: new LineChart(lines: [
                new Line<Income, int, double>(
                  data: this.incomeArr,
                  xFn: (datum) => datum.date,
                  yFn: (datum) => datum.income,
                  xAxis: new ChartAxis<int>(
                    span: IntSpan(1, maxDay),
                    tickGenerator: IntervalTickGenerator.byN(3),
                  ),
                  yAxis: new ChartAxis(
                    span: DoubleSpan(0.0, double.parse((maxIncome + 0.2).toStringAsFixed(1))),
                    tickGenerator: IntervalTickGenerator.byN(0.5),
                  ),
                  marker: const MarkerOptions(
                    paint: const PaintOptions.fill(color: Colors.deepOrange),
                    shape: MarkerShapes.circle,
                  ),
                  stroke: const PaintOptions.stroke(color: Colors.deepOrange),
                ),
              ]),
            ),
            new Expanded(
              child: new ListView.builder(
                itemCount: incomeArr.length,
                itemBuilder: (context, i) => _buildTiles(incomeArr[i]),
              ),
            ),
          ],
        ):this.has_data==2?new Center(child: new CircularProgressIndicator(),):new Center(
          child: new Container(
            width: 200.0,
            height: 200.0,
            child: new Column(
              children: <Widget>[
                new Text("暂无收入记录",style: new TextStyle(fontSize: 22.0),),
                new FlatButton(onPressed: (){
                  back();
                }, child: new Text("返回")),
              ],
            )
          ),
        ),
//          child:
      ),
    );
  }
}
